'use client';

import React from 'react';
import { EventModel } from '../lib/api';

interface Props {
  target: EventModel | null;
  actor: string;
  onClose: () => void;
  onSubmit: (message: string, mentions: string[]) => Promise<void>;
}

export function CommentDrawer({ target, actor, onClose, onSubmit }: Props) {
  const [message, setMessage] = React.useState('');
  const [mentions, setMentions] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => {
    if (!target) {
      setMessage('');
      setMentions('');
      setBusy(false);
    }
  }, [target]);

  if (!target) return null;

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!message.trim()) return;
    setBusy(true);
    try {
      const mentionList = mentions.split(',').map(m => m.replace('@', '').trim()).filter(Boolean);
      await onSubmit(message, mentionList);
      onClose();
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="drawer">
      <form className="drawer-content" onSubmit={handleSubmit}>
        <header>
          <h2>Reply as {actor}</h2>
          <span className="muted">Responding to {target.actor} on {new Date(target.created_at).toLocaleString()}</span>
        </header>
        <label>
          Message
          <textarea value={message} onChange={e => setMessage(e.target.value)} rows={5} placeholder="Leave a comment" />
        </label>
        <label>
          Mentions
          <input value={mentions} onChange={e => setMentions(e.target.value)} placeholder="@claude, @codex" />
        </label>
        <footer>
          <button type="button" className="ghost" onClick={onClose} disabled={busy}>Cancel</button>
          <button type="submit" className="primary" disabled={busy}>{busy ? 'Posting…' : 'Comment'}</button>
        </footer>
      </form>
    </div>
  );
}
